package com.farm.result;

import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import org.apache.shiro.util.StringUtils;

@Data
public class Result {

    @NonNull private int code;
    @NonNull private String msg;
    private Object data;

    private Result(@NonNull ResultCode code, String msg, Object data) {
        this.code = code.getCode();
        this.msg = StringUtils.hasLength(msg) ? msg : code.getDefMsg();
        this.data = data;
    }

    public static Result build(@NonNull ResultCode code, String msg, Object data) {
        return new Result(code, msg, data);
    }

    public static Result build(@NonNull ResultCode code, String msg) {
        return new Result(code, msg, null);
    }

    public static Result build(@NonNull ResultCode code) {
        return new Result(code, null, null);
    }

    public static Result succeed(Object data) {
        return build(ResultCode.SUCCEED, null, data);
    }

    public static Result succeed() {
        return succeed(null);
    }

    public static Result fail(String msg) {
        return build(ResultCode.FAIL, msg);
    }

    public static Result fail() {
        return fail(null);
    }

    public static Result unauthorized(String msg) {
        return build(ResultCode.UNAUTHORIZED, msg);
    }

    public static Result unauthorized() {
        return unauthorized(null);
    }

    public static Result unknown(String msg) {
        return build(ResultCode.NOT_FOUND, msg);
    }

    public static Result unknown() {
        return unknown(null);
    }

    public static Result error(String msg) {
        return build(ResultCode.NOT_FOUND, msg);
    }

    public static Result error() {
        return error(null);
    }

    public static Result judge(boolean flag, Object successData, String failMsg) {
        return flag ? succeed(successData) : fail(failMsg);
    }

    @Getter
    public enum ResultCode {

        SUCCEED(200, "成功"),
        FAIL(400, "请求异常"),
        UNAUTHORIZED(401, "未经授权"),
        NOT_FOUND(404, "页面不存在"),
        UNKNOWN_ACCOUNT(4010, "用户名不存在"),
        INCORRECT_CREDENTIALS(4011, "用户名或密码错误"),
        LOCKED_ACCOUNT(4012, "账户已被封禁"),
        INTERNAL_SERVER_ERROR(500, "业务错误");

        private final int code;
        private final String defMsg;

        ResultCode(int code, String defMsg) {
            this.code = code;
            this.defMsg = defMsg;
        }

    }
}
